/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 *         
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. Unless required by applicable law or
 * agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.rhok.ncn.communicator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.rhok.ncn.common.CommonData;
import org.rhok.ncn.datatypes.LocationData;

import android.util.Log;

/**
 * Web client for connecting to the remove server.
 * @author pfritzsche
 */
public final class WebClient {
	private static final String
		SERVER_URL = "http://needcommsnow.appspot.com/",
		TAG = "WebClient",
		TIMESTAMP = "timestamp",
		LAT = "lat",
		LNG = "lng",
		SIGNAL = "signal",
		WIFI = "wifi",
		PROVIDER = "provider";
	
	public static boolean submitData(LocationData data) throws IOException {
	    DefaultHttpClient client = new DefaultHttpClient();
	    HttpPost request = new HttpPost(SERVER_URL);

	    List<NameValuePair> nvps = new ArrayList<NameValuePair>(6);
	    nvps.add(new BasicNameValuePair(LAT, Double.toString(data.lat())));
	    nvps.add(new BasicNameValuePair(LNG, Double.toString(data.lng())));
	    nvps.add(new BasicNameValuePair(SIGNAL, Integer.toString(data.signal())));
	    nvps.add(new BasicNameValuePair(WIFI, Integer.toString(data.wifi())));
	    nvps.add(new BasicNameValuePair(TIMESTAMP, Long.toString(data.timestamp())));
	    nvps.add(new BasicNameValuePair(PROVIDER, CommonData.provider()));
	    
	    request.setEntity(new UrlEncodedFormEntity(nvps));
	    HttpResponse httpResponse = client.execute(request);
	    int status = httpResponse.getStatusLine().getStatusCode();
	    Log.d(TAG, "Server response code: " + status);

	    return status == HttpStatus.SC_OK;
	}
}